package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;

import java.util.List;

/**
 * 学生web控制器
 *
 * @author raos
 * @date 2024-12-14
 */
@Slf4j
@Mapping("/student")
@Controller
public class StudentController {

    @Inject
    private StudentService studentService;

    @Mapping("/page")
    public List<Student> page(@Param(name = "pageNum", defaultValue = "1") Integer pageNum,
                              @Param(name = "pageSize", defaultValue = "2") Integer pageSize) {
        Page<Student> page = studentService.page(new Page<>(pageNum, pageSize), QueryWrapper.create());
        log.info("总记录数=【{}】", page.getTotalRow());
        return page.getRecords();
    }

    @Mapping("/info")
    public Student info(Long userId) {
        log.info("传递参数userId=【{}】", userId);
        return studentService.findById(userId);
    }

    @Mapping("/save")
    public Student save(Student student) {
        if (student.getUserId() == null) {
            boolean save = studentService.save(student);
            log.info("新增结果：【{}】", save);
        } else {
            boolean update = studentService.updateById(student);
            log.info("修改结果：【{}】", update);
        }
        return student;
    }

    @Mapping("/del")
    public String del(Long userId) {
        if (userId == null) {
            throw new RuntimeException("删除时userId不能为空");
        }
        boolean remove = studentService.removeById(userId);
        log.info("删除结果【{}】", remove ? "成功" : "失败");
        return remove ? String.format("删除用户ID={%s}成功", userId)
                : String.format("删除用户ID={%s}失败", userId);
    }

}
